import router from "@/router";
import useUserStore from "@/stores/modules/user";
import { toast } from "@/utils/index";

// 引入 views 文件夹下所有 vue 文件
const modules = import.meta.glob("@/views/**/*.vue");
export const addDynamicRoutes = async () => {
  const userStore = useUserStore();
  try {
    // 获取用户菜单
    await userStore.getMenuList();
    // 判断当前用户有没有菜单权限
    if (!userStore.menuList.length) {
      toast("您没有菜单权限", "error");
      userStore.$reset();
      router.replace({ path: "/login" });
      return Promise.reject("No permission");
    }

    // 添加动态路由
    userStore.flatMenuList.forEach((item: any) => {
      item.children && delete item.children;
      if (item.component && typeof item.component == "string") {
        item.component = modules["/src/views" + item.component + ".vue"];
      }
      if (item.meta.isFull) {
        router.addRoute(item);
      } else {
        router.addRoute("layout", item);
      }
    });
  } catch (error) {
    userStore.$reset();
    router.replace({ path: "/login" });
    return Promise.reject(error);
  }
};
